<script setup lang="ts">
import { shallowRef } from 'vue'
import { v4 as uuidv4 } from 'uuid'
import { message } from 'ant-design-vue'
import { getImageDimensions } from '@/helper'
import type { UploadResp } from '@/extraType'
import LText from '@/components/LText.vue'
import LImage from '@/components/LImage.vue'
import StyledUploader from '@/components/StyledUploader.vue'
import type { ComponentsData } from '@/stores/editor'

interface propsType {
  // TODO 类型
  list: {}[]
  // type: 'l-text' | 'l-image' | 'l-shape'
  type: keyof typeof canvasComponentList.value
}
const props = defineProps<propsType>()
const emits = defineEmits(['on-item-click'])

const canvasComponentList = shallowRef({
  'l-text': LText,
  'l-image': LImage,
  'l-shape': ''
})

const onItemClick = (data: any) => {
  const componentData: ComponentsData = {
    id: uuidv4(),
    name: props.type,
    props: data
  }
  emits('on-item-click', componentData)
}
const onImageUploaded = async (resp: UploadResp, file: File) => {
  const componentData: ComponentsData = {
    id: uuidv4(),
    name: props.type,
    props: {}
  }
  message.success('图片上传成功')
  componentData.props.src = resp.data.urls[0]
  const { width } = await getImageDimensions(file)
  const maxWidth = 373
  componentData.props.width = `${width > maxWidth ? maxWidth : width}px`
  emits('on-item-click', componentData)
}
</script>

<template>
  <div class="create-component-list">
    <div
      class="component-item"
      v-for="(item, index) in props.list"
      :key="index"
      @click="onItemClick(item)"
    >
      <component :is="canvasComponentList[props.type]" v-bind="item"></component>
      <!-- <LText v-bind="item"></LText> -->
    </div>
    <StyledUploader
      v-if="props.type === 'l-image'"
      :show-uploaded="false"
      @success="onImageUploaded"
    ></StyledUploader>
  </div>
</template>

<style scoped lang="scss">
.create-component-list {
  position: relative;
  text-align: center;
  min-height: 400px;
  margin-left: auto;
  margin-right: auto;
}
</style>
